package org.gitee.lz.xspring.exception;

import com.tigerbrokers.bff.apihub.common.dto.pojo.v1.response.ExecResult;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * @ClassName: UnifiedExceptionHandler
 * @Description: UnifiedExceptionHandler
 * @Author: lizhen
 * @Date: 2024-01-09 16:08
 * @Version: 1.0
 **/
@Slf4j
@Component
public class UnifiedExceptionHandler {

  /**.
   * 获取Exception消息
   * @param e 异常
   * @return String
   */
  private static String getMessage(@NotNull BaseException e) {
    String message = e.getMessage();

    if (e.getResponseEnum() != null) {
      message = e.getResponseEnum().getMessage();
    }

    return message;
  }

  /**.
   * 业务异常
   * @param e 异常
   * @return 异常结果
   */
  @ExceptionHandler(value = BusinessException.class)
  public static ExecResult handleBusinessException(BaseException e) {
    log.error(e.getMessage(), e);

    return ExecResult.of(e.getResponseEnum().getRet(), getMessage(e));
  }

  /**.
   * 自定义异常
   * @param e 异常
   * @return 异常结果
   */
  @ExceptionHandler(value = BaseException.class)
  public static ExecResult handleBaseException(BaseException e) {
    log.error(e.getMessage(), e);

    return ExecResult.of(e.getResponseEnum().getRet(), getMessage(e));
  }

  /**
   * 未定义异常
   * @param e 异常
   * @return 异常结果
   */
  @ExceptionHandler(value = Exception.class)
  public static ExecResult handleException(Exception e) {
    log.error(e.getMessage(), e);

    BaseException baseException = new BaseException(e.getCause().getMessage());
    String message = getMessage(baseException);

    return ExecResult.of(ExecResult.CODE_UNKNOWN_ERROR, message);
  }
}

